<?php

class SupplierDispatchesController extends AppController {

    var $name = 'SupplierDispatches';
    var $pageTitle = 'Dispatch Information';
    var $viewPath = 'suppliers/supplier_dispatches';
    var $uses = array('SDH', 'SD', 'Supplier', 'Product', 'CPS', 'Product', 'RunningNo', 'Site', 'ProductSerial', 'DispatchStatus', 'Customer', 'Warehouse', 'VSCustomer', 'UserCoH');

    function beforeFilter() {
        parent::beforeFilter();
        $this->set('parentNav', 'supplier_dispatches');
    }

    function display() {
        parent::display('SDH');

        $op = array(
            'dispatch_no' => 'LIKE',
            'customer_id' => '=',
            'site_id' => '=',
            'dispatch_status_id' => '=',
        );

        $this->_checkCustomerOnHand('SDH');
        $this->_checkSupplier('SDH');

        $this->_checkBetweenSearch('SDH', 'dispatch_date');
        $this->_paging('SDH', $op);
    }

    function save() {
        $sdh_id = null;
        $is_success = true;
        $collector_id = $this->Session->read('Auth.User.id');
        $supplier_id = $this->Auth->user('supplier_id');

        // เรียงลำดับรายการใหม่ กรณีลบแถว Index เปลี่ยน
        $this->adjustRowIndex($this->data['SD']);

        // ตรวจสอบว่ามีสินค้าอยู่ในใบ ItsStockInHead
        if (count($this->data['SD']) == 0) {
            $this->Session->setFlash("Dispatch must have at least one product !!!.", 'flash/fail');
        } else {
            $this->SDH->query("BEGIN");

            if ($this->data['mode'] == 'add') {
                $year = $this->Utility->getThaiYear();
                // Dispatch no. format {ITS}{YEAR}1{RUNNO}
                $runno = $this->RunningNo->getNextStockNo(RunningNo::SUPPLIER_DISPATCH, $year, null, 5);
                $this->data['SDH']['dispatch_no'] = 'ITS' . $year . '1' . $runno;
            } else {
                // update Dispatch ใบเก่าว่าถูก revise
                $this->SDH->id = $this->data['SDH']['old_id'];
                $this->SDH->saveField('dispatch_status_id', DispatchStatus::REVISE_STATUS);

                $this->SD->contain();
                $sds = $this->SD->findAllBySupplierDispatchHeadId($this->SDH->id);
                foreach ($sds as $sd) {
                    $this->ProductSerial->contain();
                    $is_success &= $this->ProductSerial->updateAll(
                                    array('is_active_flag' => 0),
                                    array(
                                        'its_stock_out_id' => $sd['SD']['id'],
                                        'its_stock_out_type' => SD::ITS_STOCK_OUT_TYPE
                                    )
                    );
                }
            }
            $this->data['SDH']['dispatch_status_id'] = DispatchStatus::ON_DISPATCH_STATUS;
            $this->data['SDH']['collector_id'] = $collector_id;
            $this->data['SDH']['supplier_id'] = $supplier_id;

            // Save SDH && SD
            if ($this->SDH->saveAll($this->data, array('validate' => 'first', 'atomic' => false))) {
                $sdh_id = $this->SDH->id;

                foreach ($this->data['SD'] as $sd) {
                    $product_id = $sd['product_id'];
                    $cps_id = $sd['cust_product_site_id'];
                    $qty = $sd['qty'];

                    $this->Product->id = $product_id;
                    $this->Product->saveField('last_dispatch_date', date('Y-m-d'));
                    $this->Product->saveField('last_dispatch_customer_id', $this->data['SDH']['customer_id']);

                    // update CPS ว่าถูกส่งมาจาก Supplier
                    $this->CPS->id = $cps_id;
                    $this->CPS->saveField('dispatch_from', SUPPLIER_PREFIX);
                    // update ราคาขายล่าสุด
                    $this->CPS->saveField('price', $sd['price']);

                    //ดึงรายการ SD เพื่อสร้าง ProductSerial
                    $this->SD->contain();
                    $cs = $this->SD->find('first',
                                    array(
                                        'conditions' => array(
                                            'supplier_dispatch_head_id' => $sdh_id,
                                            'product_id' => $product_id
                                        ),
                                        'fields' => array('id', 'cust_product_site_id')
                                    )
                    );

                    // ดึง Stock out priority ล่าสุดของ CPS นี้ // null ถ้าไม่มีเลย cast type
                    $sop = (int) $this->ProductSerial->field('stock_out_priority', array(
                                'product_id' => $product_id,
                                'cust_product_site_id' => $cs['SD']['cust_product_site_id'],
                                'is_active_flag' => true,
                                    ),
                                    'stock_out_priority DESC'
                    );

                    // สร้าง รายการ Product Serial
                    // นับจำนวน Product Serial ถ้าใน index ไม่เท่า Qty ให้สร้าง Product Serial เท่า qty
                    $product_serial_count = count($sd['ProductSerial']);
                    if ($qty != $product_serial_count) {
                        $product_serial_count = $qty;
                    }
                    
                    for ($j = 0; $j < $product_serial_count; ++$j) {
                        $data = array();
                        $data['ProductSerial']['id'] = null;
                        $data['ProductSerial']['cust_product_site_id'] = $cs['SD']['cust_product_site_id'];
                        $data['ProductSerial']['product_id'] = $product_id;
                        $data['ProductSerial']['its_stock_out_id'] = $cs['SD']['id'];
                        $data['ProductSerial']['its_stock_out_type'] = SD::ITS_STOCK_OUT_TYPE;
                        $data['ProductSerial']['price'] = $sd['price'];
                        $data['ProductSerial']['stock_out_priority'] = ++$sop;
                        $data['ProductSerial']['serial_no'] = !empty($sd['ProductSerial'][$j]['serial_no']) ? $sd['ProductSerial'][$j]['serial_no'] : null;
                        $data['ProductSerial']['other_information'] = !empty($sd['ProductSerial'][$j]['other_information']) ? $sd['ProductSerial'][$j]['other_information'] : null;
                        $this->ProductSerial->create();
                        $this->ProductSerial->save($data);
                    }
                }
            } else {
                $is_success = false;
            }
            if ($is_success) {
                $this->SDH->query("COMMIT");
                ;
                $sdh_id = $this->SDH->id;
                $this->Session->setFlash("Dispatch no {$this->data['SDH']['dispatch_no']} save succesfull.", 'flash/ok');
            } else {
                $this->SDH->query("ROLLBACK");
                $this->Session->setFlash("Dispatch save fail!!!.", 'flash/fail');
            }
        }
        $this->data['SD'] = null;
        $this->data['SDH']['customer_id'] = null;
        $this->setAction('view', $sdh_id);
    }

    function view($id = null) {
        $revise = isset($this->passedArgs['revise']) ? $this->passedArgs['revise'] : false;
        $supplier_id = $this->Auth->user('supplier_id');
        if ($id != null) {
            $this->SDH->contain(array('Customer', 'Site', 'DispatchStatus', 'Supplier',
                'SD' => array('Product' => array('supplier_part_no', 'text', 'Unit'), 'CPS' => array('stock_code', 'text'))));
            $this->data = $this->SDH->findById($id);

            // ถ้าเป็น On Dispatch สามารถเลือก Revise ได้ และ see price adjustment ได้
            if ($this->data['SDH']['dispatch_status_id'] == DispatchStatus::ON_DISPATCH_STATUS) {
                $this->set('canRevise', true);
            }

            if ($revise == false) {
                $this->_neighbors($id, $this->SDH, array('fields' => array('id', 'dispatch_no')));
                $this->set('mode', 'edit');
            } else {
                $dispatch_no = $this->data['SDH']['dispatch_no'];
                // Revise ครั้งแรก
                if (strlen($dispatch_no) < 12) {
                    $this->data['SDH']['dispatch_no'] = $dispatch_no . ' Rev. 1';
                } else {
                    $revise_no = (int) substr($dispatch_no, 17) + 1;
                    $this->data['SDH']['dispatch_no'] = substr($dispatch_no, 0, 12) . ' Rev. ' . $revise_no;
                }
                // clear ID เดิม
                $this->data['SDH']['old_id'] = $this->data['SDH']['id'];
                $this->data['SDH']['id'] = null;
//                foreach ($this->data['SD'] as &$csi) {
//                    $csi['id'] = null;
//                }

                $this->SDH->DispatchStatus->id = DispatchStatus::ON_DISPATCH_STATUS;
                $this->set('dispatchStatus', $this->SDH->DispatchStatus->field('title'));
                $this->set('mode', 'revise');
            }
        } else {
            $this->DispatchStatus->id = DispatchStatus::ON_DISPATCH_STATUS;
            $this->set('dispatchStatus', $this->DispatchStatus->field('title'));
            // แสดงรายการเฉพาะที่ User นี้รับผิดชอบ
            $customers = $this->UserCoH->listCustomerOnHand($this->Auth->user('id'));
            $this->set('customers', $this->VSCustomer->find('list', array('conditions' => array('supplier_id' => $supplier_id, 'id' => $customers))));
            $this->Supplier->id = $supplier_id;
            $this->set('supplierName', $this->Supplier->field('name'));
            $this->set('mode', 'add');
        }
    }

    function print_view($id, $for_customer = false) {
        $this->layout = 'print';
        $this->SDH->contain(array('Customer', 'Site', 'Supplier',
            'SD' => array(
                'Product' => array('supplier_part_no', 'text', 'Unit'),
                'CPS' => array('stock_code', 'text'),
                'ProductSerial' => array(
                    'conditions' => array(
                        'OR' => array(
                            'serial_no IS NOT NULL',
                            'other_information IS NOT NULL'
                        )
                    )
                )
                )));
        $this->data = $this->SDH->findById($id);

        if ($for_customer == false) {
            $this->render('print_view');
        } else {
            $this->render('print_view_for_customer');
        }
    }

    function popup_search() {
        parent::popup_search();

        // แสดงรายการเฉพาะที่ User นี้รับผิดชอบ
        $this->set('customers', $this->VSCustomer->findListByCustomerOnHand($this->Auth->user('id'), $this->Auth->user('supplier_id')));
        $this->set('dispatchStatuses', $this->DispatchStatus->find('list', array('field', array('id', 'title'))));
        $this->set('popupWidth', 500);
    }

    /**
     * ค้นหา Product จาก supplier part no, site ที่เลือก
     * @param string $part_no
     * @param int $site_id
     */
    function json_find_by_part_no_site_id() {
        $this->layout = 'ajax';
        // ค้นหาข้อมูลโดย part no และ customer id
        $this->CPS->contain(array(
            'Product' => array('Unit')
                )
        );
        $data = $this->CPS->find('first', array(
                    'conditions' => array(
                        'Product.supplier_part_no' => $this->data['part_no'],
                        'CPS.site_id' => $this->data['site_id']
                    )
                        )
        );

        // ถ้าไม่มีเอาแค่ product อย่างเดียว
        if ($data == false) {
            $data = $this->Product->find('first', array(
                        'conditions' => array(
                            'Product.supplier_part_no' => $this->data['part_no'],
                        )
                            )
            );
        }

        $this->set('data', $data);
        // view เก็บอยู่ใน element
        $this->viewPath = 'elements';
        $this->render('ajax/json');
    }

}

?>
